# -*- encoding: utf-8 -*-
##############################################################################
#
#
##############################################################################

from datetime import datetime
from odoo.tools import float_compare
from odoo.exceptions import except_orm, Warning, RedirectWarning
import odoo.addons.decimal_precision as dp
from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT
from odoo import api, fields, models, _
from odoo.exceptions import ValidationError


class sale_order(models.Model):
    _inherit = 'sale.order'

    err_mess = fields.Text(string=u'错误信息')

    @api.multi
    def action_confirm(self):
        for order in self:
            if not order.err_mess:
                order.err_mess = u""
            if order.pass_credit:
                continue
            # 信用额度限制
            err = self.check_credit_limit_ok()
            if not err:
                order.err_mess += u'订单已超过信用额度，请核实账款或申请增加信用额度.\n(信用额度<=(应收账款+未确认账款+在途订单金额))。该情况您可以请求特批。\n'
            # 逾期账单限制
            if order.partner_id.switch_of_credit and order.partner_id.line_of_credit < order.partner_id.date_out_credit:
                order.err_mess += u'对不起,此单客户存在逾期账款,不允许直接确认订单.请请求特批!\n'
            if order.err_mess:
                raise ValidationError(order.err_mess)
                # raise ValidationError(u'对不起,此单客户存在逾期账款,不允许直接确认订单.请请求特批')
        return super(sale_order, self).action_confirm()

    @api.multi
    def action_confirm_with_credit(self):
        for order in self:
            order.pass_credit = True
            order.action_confirm()

    pass_credit = fields.Boolean(u'跳过额度与价格限制', default=False, copy=False)

    # pass_need = fields.Boolean(u'需要特批',default=False,copy=False)

    @api.multi
    def check_credit_limit_ok(self):
        self.ensure_one()
        if not self.partner_id.red_line_of_credit:
            return True
        domain = [
            ('order_id.partner_id', '=', self.partner_id.id),
            ('order_id.state', 'in', ['sale', 'done'])]
        order_lines = self.env['sale.order.line'].search(domain)
        # 计算没开票的订单金额
        to_invoice_amount = 0.0
        for line in order_lines:
            # not_invoiced is different from native qty_to_invoice because
            # the last one only consider to_invoice lines the ones
            # that has been delivered or are ready to invoice regarding
            # the invoicing policy. Not_invoiced consider all
            not_invoiced = line.product_uom_qty - line.qty_invoiced
            price = line.price_unit * (1 - (line.discount or 0.0) / 100.0)
            taxes = line.tax_id.compute_all(
                price, line.order_id.currency_id,
                not_invoiced,
                product=line.product_id, partner=line.order_id.partner_id)
            to_invoice_amount += taxes['total_included']

        # 未确认的发票金额,不属于销售订单
        domain = [
            ('invoice_id.partner_id', '=', self.partner_id.id),
            ('invoice_id.state', '=', 'draft'),
            ('sale_line_ids', '=', False)]
        draft_invoice_lines = self.env['account.invoice.line'].search(domain)
        draft_invoice_lines_amount = 0.0
        for line in draft_invoice_lines:
            price = line.price_unit * (1 - (line.discount or 0.0) / 100.0)
            taxes = line.invoice_line_tax_ids.compute_all(
                price, line.invoice_id.currency_id,
                line.quantity,
                product=line.product_id, partner=line.invoice_id.partner_id)
            draft_invoice_lines_amount += taxes['total_included']
        # 可用信用额度= 客户信用额度-欠款-待开票金额-草稿发票金额
        available_credit = self.partner_id.credit_limit - self.partner_id.credit - to_invoice_amount - draft_invoice_lines_amount
        if self.amount_total > available_credit:
            return False
        return True
